from sockets.frontsocket import sio
from sockets.agvsocket import AgvSocket

from settings.settings import settings

from role.admin import Admin

sio_manage = AgvSocket()
sio_control = sio_manage.get(settings.AGV_PORT_CONTROL)


async def init_control_event():
    await init_motion_control()


async def init_motion_control():
    @sio.on("forward")
    async def forward(sid, speed):
        await move('up', sid, speed)

    @sio.on("backward")
    async def backward(sid, speed):
        await move('down', sid, speed)

    @sio.on("turnleft")
    async def turnleft(sid, r_speed):
        await move('left', sid,  r_speed)

    @sio.on("turnright")
    async def turnright(sid, r_speed):
        await move('right', sid,  r_speed)

    @sio.on("stop")
    async def stop(sid):
        await move('stop', sid,  speed=0)


async def move(direction, sid, speed):
    # 移动agv的权限检查
    if not Admin().is_admin(sid):
        return
    if direction == 'up':
        sio_manage.send(sio_control, 1, 2010, {"vx": speed, "vy": 0.000000, "w": 0.000000})
    elif direction == 'down':
        sio_manage.send(sio_control, 1, 2010, {"vx": -speed, "vy": 0.000000, "w": 0.000000})
    elif direction == 'left':
        sio_manage.send(sio_control, 1, 2010, {"vx": 0.000000, "vy": 0.000000, "w": speed})
    elif direction == 'right':
        sio_manage.send(sio_control, 1, 2010, {"vx": 0.000000, "vy": 0.000000, "w": -speed})
    elif direction == 'stop':
        sio_manage.send(sio_control, 1, 2000)

    # 接受数据
    # res = sio_manage.receive(sio_control)
    # await sio.emit("completed", res, room="agv")
